package com.zqwm.fly.utils;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;

@SuppressWarnings("all")
@Component
public class FtpUploader {

    private static final Logger logger = LoggerFactory.getLogger(FtpUploader.class);

    @Value("${ftp.connection.host}")
    private String host;
    @Value("${ftp.connection.port}")
    private int port;
    @Value("${ftp.connection.user}")
    private String user;
    @Value("${ftp.connection.password}")
    private String password;
    @Value("${ftp.upload.basepath}")
    private String ftpPath;
    private FTPClient client = null;

    FtpUploader() {
        client = new FTPClient();
    }

    public boolean connect() {

        boolean result = false;
        if (client.isConnected() == false) {
            try {
                client.connect(InetAddress.getByName(host), port);
                if (client.login(user, password) == true) {
                    client.setFileType(FTPClient.BINARY_FILE_TYPE);
                    int reply = client.getReplyCode();
                    if (FTPReply.isPositiveCompletion(reply) == true) {
                        result = true;
                    } else {
                        client.logout();
                        client.disconnect();
                    }
                } else {
                    logger.error("用户名密码不匹配");
                    client.disconnect();
                }


            } catch (Exception e) {
                logger.error("连接FTP服务器报错:", e);
            }
        } else {
            result = true;
            logger.info("已经连接到FTP服务器");
        }
        return result;
    }

    public void changeWorkingDir(String ftpPath) {
        try {
            if (ftpPath != null && !"".equals(ftpPath)) {
                boolean success = client.changeWorkingDirectory(ftpPath);
                if (success == false) {
                    StringTokenizer token = new StringTokenizer(ftpPath, "\\//");
                    while (token.hasMoreTokens()) {
                        String path = token.nextToken();
                        client.makeDirectory(path);
                        client.changeWorkingDirectory(path);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("切换文件夹报错:", e);
        }
    }

    public boolean uploadFile(String phone, String ftpFilename, InputStream input) {
        boolean result = false;
        String driverPath = ftpPath + "driver-" + phone;
        try {
            client.enterLocalPassiveMode();
            changeWorkingDir(driverPath);

            result = client.storeFile(ftpFilename, input);
            if (result == true) {
                logger.info("FTP服务器上传文件:" + ftpPath + File.separator + ftpFilename + ":" + "OK！");
            } else {
                logger.info("FTP服务器上传文件:" + ftpPath + File.separator + ftpFilename + ":" + "Failure！");
            }
        } catch (Exception e) {
            logger.error("上传文件报错:", e);
        } finally {
            try {
                if (null != input) {
                    input.close();
                }
            } catch (IOException e) {}
        }
        return result;
    }

    public Map<String, String> changeFileNames(String ftpPath, Map<String, Object> fileset) {
        Map<String, FTPFile> fileMap = new HashMap<String, FTPFile>();
        Map<String, String> fileAllNames = new HashMap<String, String>();


        if (null != fileset && !fileset.isEmpty()) {
            Iterator<String> its = fileset.keySet().iterator();
            while (its.hasNext()) {
                String key = its.next();
                fileMap.put(key, null);
            }
        }

        try {

            //ftp文件上传模式设置
            client.enterLocalPassiveMode();
            changeWorkingDir(ftpPath);
            FTPFile[] filenames = client.listFiles();
            for (int i = 0; i < filenames.length; i++) {
                Iterator<String> itsFTpfiles = fileMap.keySet().iterator();
                while (itsFTpfiles.hasNext()) {
                    String fileNamePart = itsFTpfiles.next();
                    if (filenames[i].getName().contains(fileNamePart)) {
                        if (null == fileMap.get(fileNamePart)) {
                            fileMap.put(fileNamePart, filenames[i]);
                        } else {
                            if (fileMap.get(fileNamePart).getTimestamp().getTime().getTime() < filenames[i].getTimestamp().getTime().getTime()) {
                                client.deleteFile(fileMap.get(fileNamePart).getName());
                                fileMap.put(fileNamePart, filenames[i]);
                            } else {
                                client.deleteFile(filenames[i].getName());
                            }
                        }
                    }
                }
            }
            if (!fileMap.isEmpty()) {
                Iterator<String> changefileits = fileMap.keySet().iterator();
                while (changefileits.hasNext()) {
                    String changefilekey = changefileits.next();
                    if (null != fileMap.get(changefilekey)) {
                        String filename = fileMap.get(changefilekey).getName();
                        if (fileMap.get(changefilekey).getName().indexOf("_bak") >= 0) {
                            client.rename(fileMap.get(changefilekey).getName(), fileMap.get(changefilekey).getName().replace("_bak", ""));
                            fileAllNames.put(changefilekey, filename.replace("_bak", ""));
                        } else {
                            fileAllNames.put(changefilekey, filename);
                        }
                    }
                }
            }

        } catch (Exception e) {
            logger.error("下载文件报错！", e);
        }
        return fileAllNames;
    }
}
